//
//  AYuEmoticonToolbar.swift
//  SHWeibo3
//
//  Created by 余伟康 on 16/7/29.
//  Copyright © 2016年 wangce. All rights reserved.
//

import UIKit

private let tagNum = 2000
// 按钮枚举
enum AYuEmoticonToolbarType: Int{
    // 默认
    case Default = 0
    // Emoji
    case Emoji = 1
    // 浪小花
    case lxh = 2
}


class AYuEmoticonToolbar: UIStackView {
    
    // 定义一个闭包
    var closure:((type:AYuEmoticonToolbarType)->())?
    
    // 当前选中的按钮
    var currentButton: UIButton?
    
    // MARK: - 供外界调用方法
    func setupCurrentButton(tag: Int){
        let button = viewWithTag(tag + tagNum) as! UIButton
        setupCurrentButtons(button)
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - 设置视图
    private func setupUI(){
        // 设置排列方向
        axis = .Horizontal
        // 填充效果 
        distribution = .FillEqually
        
        addChildButton("left", title: "默认", type: .Default)
        addChildButton("mid", title: "Emoji", type: .Emoji)
        addChildButton("right", title: "浪小花", type: .lxh)
        
    }
    
    
    func addChildButton(imgName: String,title: String,type:AYuEmoticonToolbarType){
        let button = UIButton()
        // 默认情况下 默认按钮被选中
        if type == .Default{
            setupCurrentButtons(button)
        }
        
        button.tag = type.rawValue + tagNum
        // 添加点击事件
        button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTitle(title, forState: UIControlState.Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imgName)_normal"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "compose_emotion_table_\(imgName)_selected"), forState: UIControlState.Selected)
        addArrangedSubview(button)
    }
    
    // MARK: - 监听方法
    func buttonClick(button: UIButton) {
        setupCurrentButtons(button)
        // 执行闭包
        closure?(type: AYuEmoticonToolbarType(rawValue: button.tag - tagNum)!)
    }
    
    // MARK: - 设置当前选中的按钮
    func setupCurrentButtons(button: UIButton){
        if button == currentButton{
            return
        }
        currentButton?.selected = false
        button.selected = true
        currentButton = button
    }
    
    
    
    

}
